import { useControllableValue } from "ahooks";
import { Form, Input, Modal } from "antd";
import React from "react";
import styles from "./index.module.scss";

type Props = {
  type: "add" | "edit";
  visable: boolean;
  data?: { name: string; email: string };
  handleOnOk?: (values: any) => void;
  handleOnCancel?: () => void;
};

const UserForm: React.FC<Props> = (props) => {
  console.log(props);

  const [form] = Form.useForm();
  const [name, setName] = useControllableValue(props, {
    valuePropName: "name",
    defaultValue: "",
  });
  const [email, setEmail] = useControllableValue(props, {
    valuePropName: "email",
    defaultValue: "",
  });

  const handleOnOk = () => {
    form.validateFields().then((res) => {
      form.resetFields();
      props.handleOnOk(res);
    });
  };

  return (
    <div>
      <Modal
        onOk={handleOnOk}
        onCancel={props.handleOnCancel}
        open={props.visable}
        title={props.type === "add" ? "新增" : "修改"}
        okText="确认"
        cancelText="取消"
        width={400}
      >
        <Form
          form={form}
          labelAlign="left"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          layout="horizontal"
          className={styles.form}
          autoComplete="off"
        >
          <Form.Item name="name" label="用户名:">
            <Input
              placeholder="请输入用户名"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </Form.Item>
          <Form.Item name="email" label="邮箱:">
            <Input
              placeholder="请输入邮箱"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserForm;
